package tzhomestudio.framework.implementation.log_service;

import tzhomestudio.framework.interfaces.log_service.ILogger;

/**
 * This class realizes interface ILogger.
 * Messages are displayed on standard output.
 *
 * @author Timur Zolotuhin (e-mail: tzolotuhin@gmail.com)
 */
public class ConsoleLogger implements ILogger {
    // Main data
    private boolean enableDebugMode;

    // Mutex
    private final Object generalMutex = new Object();

    @Override
    public void enableDebugMessage(boolean enable) {
        synchronized (generalMutex) {
            enableDebugMode = enable;
        }
    }

    @Override
    public void printDebug(String message) {
        synchronized (generalMutex) {
            if (!enableDebugMode) return;

            System.out.println("[DEBUG] : " + message);
        }
	}

    @Override
    public void printDebug(String message, Throwable ex) {
        synchronized (generalMutex) {
            if (!enableDebugMode) return;

            printDebug(message);
            printException(ex);
        }
    }

    @Override
    public void printError(String message) {
        synchronized (generalMutex) {
            System.err.println("[ERROR] : " + message);
        }
	}

    @Override
    public void printError(String message, Throwable ex) {
        synchronized (generalMutex) {
            printError(message);
            printException(ex);
        }
    }

    @Override
    public void printInfo(String message) {
        synchronized (generalMutex) {
            System.out.print("[INFO] : "+message+"\n");
        }
	}

    public void printException(Throwable ex) {
        synchronized (generalMutex) {
            if (ex == null) return;

            System.err.println("[TRACE START] Message = " + ex.getMessage());
            for (int i = 0; i < ex.getStackTrace().length; i++) {
                System.err.println("[TRACE] : " + ex.getStackTrace()[i].toString());
            }
            System.err.println("[TRACE END]");
        }
	}

    @Override
    public void printErrorAndThrowRuntimeException(String message) throws RuntimeException {
        synchronized (generalMutex) {
            printError(message);
            throw new RuntimeException(message);
        }
    }

    @Override
    public String getLoggerInfo() {
        synchronized (generalMutex) {
            return("This logger uses standard out/err channels");
        }
	}
}
